<?php

namespace app\common\model\banxi\organization;

use app\common\enums\organization\OrganizationUpTypeEnum;
use app\common\model\common\BaseModel;
use think\model\concern\SoftDelete;

/**
 * 机构等级配置
 */
class OrganizationLevelRw extends BaseModel
{
    use SoftDelete;

    protected $name = 'banxi_organization_level_rw';

    protected $autoWriteTimestamp = true;

    protected $deleteTime = 'del';

    protected $defaultSoftDelete = 0;

    protected $append = [
        'upTypeCn'
    ];

    protected $type = [
        'id' => 'string',
        'del' => 'string',
        'createTime' => 'timestamp:Y-m-d H:i:s',
        'updateTime' => 'timestamp:Y-m-d H:i:s',
    ];


    //-----------------------------------------------------------------------------------
    //｜                                   获取器                                       ｜
    //-----------------------------------------------------------------------------------


    public function getUpTypeCnAttr($value, $data): string
    {
        $value = $value ?: ($data['upType'] ?? '');
        return (new OrganizationUpTypeEnum())->getDescription($value) ?? '';
    }

    //-----------------------------------------------------------------------------------
    //｜                                   处理方法                                       ｜
    //-----------------------------------------------------------------------------------

    //添加记录
    public function addUpLevelRw($organizationId, $beforeLevel, $beforeLevelName, $afterLevel, $afterLevelName, $upType)
    {
        return $this->save([
            'organizationId' => $organizationId,
            'beforeLevel' => $beforeLevel,
            'beforeLevelName' => $beforeLevelName,
            'afterLevel' => $afterLevel,
            'afterLevelName' => $afterLevelName,
            'upType' => $upType,
            'date' => date('Y-m-d H:i:s')
        ]);
    }

    public function getListPage($where, $page = "1", $limit = 10)
    {
        return $this->with([
            'organizationBaseInfo' => function ($query) {
                $query->field('id,name,managerName');
            }])->where($where)->order(['id' => 'desc'])->paginate([
            'page' => $page,
            'list_rows' => $limit
        ])->each(function ($item) {
            if ($item['organizationId'] == 0) {
                $item['organizationBaseInfo'] = (new Organization())->getOrganizationInfo();
            }
        });
    }
    //-----------------------------------------------------------------------------------
    //｜                                   模型关联                                       ｜
    //-----------------------------------------------------------------------------------

    public function organizationBaseInfo()
    {
        return $this->hasOne(Organization::class, 'id', 'organizationId');
    }

}